package com.warm.androidstudy.view.banner;

import androidx.lifecycle.Observer;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.warm.androidstudy.R;
import com.warm.androidstudy.view.banner.bean.BannerBean;
import com.warm.androidstudy.view.banner.model.BannerViewModel;
import com.warm.androidstudy.common.BaseActivity;
import com.warm.androidstudy.databinding.ActivityBannerBinding;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

public class BannerActivity extends BaseActivity<BannerViewModel, ActivityBannerBinding> {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_banner;
    }

    @Override
    protected void init() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        initBanner();
        initListener();
    }


    private void initListener() {
        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewModel.getBanners();
            }
        });

        mViewModel.getLiveData().observe(this, new Observer<List<BannerBean>>() {
            @Override
            public void onChanged(List<BannerBean> bannerBeans) {
                updateBanner(bannerBeans);
            }
        });

    }

    private void initBanner() {
        binding.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //这是给banner添加图片加载器
        binding.banner.setImageLoader(new GlideImageLoader());
    }


    private void updateBanner(List<BannerBean> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        List<String> urls = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            urls.add(data.get(i).getImagePath());
            titles.add(data.get(i).getTitle());
        }
        binding.banner.setBannerTitles(titles);
        binding.banner.setImages(urls);
        binding.banner.start();
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(imageView).load(path)
                    .apply(new RequestOptions().placeholder(R.mipmap.ic_launcher))
                    .into(imageView);
        }
    }



}